package com.yang.gson;

import java.lang.reflect.Type;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class GsonTest {

	/**
	 *  将java对象转换为json字符串
	 */
	@Test
	public void test1(){
		Cat cat = new Cat("red", 1);
		Gson gson = new Gson();
		//1.
		String temp = gson.toJson(cat);
		System.out.println(temp);
		//2.
		gson = new GsonBuilder().setPrettyPrinting().create();
		temp = gson.toJson(cat);
		System.out.println(temp);
	}
	/**
	 *  将属性中含泛型的java对象转换为json字符串
	 */
	@Test
	public void test4(){
		Cat cat = new Cat("red", 1);
		NewCat<Cat> cat2 = new NewCat<Cat>(cat, "tom");
		Gson gson = new Gson();
		//1.
		String temp = gson.toJson(cat2);
		System.out.println(temp);
		//2.
		Type fooType = new TypeToken<NewCat<Cat>>() {}.getType();
		temp = gson.toJson(cat2, fooType);
		System.out.println(temp);//{"t":{"color":"red","age":1},"name":"tom"}
		//3.解析{"t":{"color":"red","age":1},"name":"tom"}
		JsonParser parser = new JsonParser();
		JsonObject jsonObject = parser.parse(temp).getAsJsonObject();
		System.out.println(gson.fromJson(jsonObject.getAsJsonObject("t"),Cat.class));
		System.out.println(jsonObject.get("name").getAsString());
	}
	/**
	 *  将json字符串转为java对象
	 */
	@Test
	public void test2(){
		String temp = "{\"color\":\"red\",\"age\":1}";
		Gson gson = new Gson();
		Cat cat = gson.fromJson(temp, Cat.class);
		System.out.println(cat);
	}
	/**
	 *  组装json字符串
	 */
	@Test
	public void test3(){
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("name", "tom");
		jsonObject.addProperty("isOld", true);
		JsonObject jsonObject1 = new JsonObject();
		jsonObject1.addProperty("name", "lily");
		jsonObject.add("friend", jsonObject1);
		System.out.println(jsonObject);
	}
}
